<template>
  <div class="c-widget" :style="styleFilter(element.style)">
    <Widget
      ref="widget"
      @cellClick="handleCellClick"
      showTitle
      v-if="option"
      :widgetType="widgetType"
      :option="option"
      :loading="isLoading"
      @pageChange="handlePageChange" />
  </div>
</template>

<script>
import mixin from "../analysisMixin"
import Widget from "@/views/dashboard/EditVisualizationComponent/Widget"
import { getProps } from "./attr"
import { analysisComponentUpdateTypes } from "../../lib/const"
// import { getWidgetOpitons } from "../../../../../utils/getWidgetOpitons"
import { getData, getParams, updateAllAnalysisComponent } from "../../lib/analysisData"
import EventBus from '../../EventBus'
import { legendList, getWidgetOpitons } from "../../../common/Widget/option.js"
export default {
  mixins: [mixin],
  components: {
    Widget,
  },
  data () {
    // console.log(getWidgetOpitons(this.value.params, []))
    return {
      // option: {}
      // option: getWidgetOpitons(this.value.params, [])
    }
  },
  methods: {
    /**
     * 获取业务组件的options
     * @param { Object | undefined } pageParams
     * @returns
     */
    getOptions (pageParams) {
      this.isLoading = true
      // 获取图标类型
      this.widgetType = legendList.find(item => item.id === this.value.dasChartTypeId)?.widget || 'Table'
      const {
        source, // 源字段
        target, // 目标字段列表
        value, // 值
        colType, // 字段类型
      } = this.$store.state.lowCode.jumpFilterData
      // 组件key和字段名
      const targetValue = target?.find(item => item.split('/')[0] === this.element.key)
      let jumpFilterData
      if (targetValue) {
        const arr = targetValue.split('/')
        jumpFilterData = {
          enName: arr[1],
          value: value,
          id: arr[2],
          type: arr[3],
          colType
        }
      }
      this.value.componentPageId = this.element.key
      getData(this.isPreview, this.value, this.filterKeys, jumpFilterData, pageParams)
      .then(({ params, data = [] }) => {
        this.isLoading = false
        this.value.params = {
          ...this.value.params,
          ...params
        }

        params = {
          ...params,
          ...(pageParams || {})
        }
        this.option = getWidgetOpitons(params, data, JSON.parse(this.value.chartStyle.replaceAll('\"{', '{').replaceAll('}\"', '}')))
        this.updateTitle()
      })
    },
    handleCellClick ({ type, params }, options) {
      console.log(type)

      if (!this.isPreview) {
        return
      }
      if (type === 'click') {
        this.handleClick(params, options)
      } else if (type === 'dblclick') {
        this.handleDbClick(params, options)
      }
    },
    handleDbClick (cell, options) {
      // 双击跳转
      console.log(cell, this.value, options)
      const {
        isFilter,
        openType,
        source,
        target,
        targetPage,
        targetType,
        targetAddress,
        isEnable
      } = this.element.jump
      if (!isEnable) {
        return false
      }
      if (targetType === 'board') {
        if (!targetPage) {
          return false
        }
        let filter = {}

        // 当前是否选择了过滤字段
        // 当前是否选择了数据源
        // 当前是否选择了目标组件字段
        // 只有当上述三条件成立,过滤才生效
        if (isFilter && source && target.length > 0) {
          filter = this.getFilterData(cell, source, target, this.element.key)
        }
        const query = {
          // name: 'agileKanbanPreview',
          path: '/quote/multidimensionalAnalysis/agileKanbanPreview',
          query: {
            id: targetPage,
            filter: encodeURIComponent(JSON.stringify(filter)),
            type: 'jump'
          },
          // params: {
          //   type: 'open'
          // }
        }
        console.log(query)
        if (openType === 'target') {
          this.$router.push(query)
        } else {
          this.$router.replace(query)
        }
      } else if (targetType === 'link') {
        window.open(targetAddress, openType)
      }
    },
    handleClick (cell, options) {
      console.log(cell)

      // 单击联动
      const {
        source,
        componentList,
        isEnable
      } = this.element.linkage
      if (!isEnable) {
        return false
      }
      // 已选择的目标组件
      const checkComponentList = componentList.filter(item => item.isCheck)
      // 数据源字段为空或没有目标组件
      if (!source || checkComponentList.length === 0) {
        return
      }
      const target = checkComponentList

      const filter = this.getFilterData(cell, source, target, this.element.key)
      const { linkageFilterData } = this.$store.state.lowCode
      const index = linkageFilterData.findIndex(item => item.key === filter.key)
      if (index > -1) {
        linkageFilterData[index] = filter
      } else {
        linkageFilterData.push(filter)
      }
      console.log(linkageFilterData)
      this.$store.commit('lowCode/setLinkageFilterData', linkageFilterData)
      // 更新被关联的组件
      updateAllAnalysisComponent(false, target.map(item => item.key), analysisComponentUpdateTypes.linkage)
    },
    getFilterData (cell, source, target, componentKey) {
      let filter
      let value
      let colType // 值类型,是string还是date
      const getChartData = () => {
        // 系列名
        const {
          enName: keyName,
          colType: keyColType
        } = this.value.params.dimensions.find(item => item.type === 1)
        // 值名
        const {
          enName: valueName,
          colType: valueColType
        } = this.value.params.dimensions.find(item => item.type === 3)
        // 获取点击得到的所有数据
        const itemData = {
          [keyName]: cell.name,
          [valueName]: cell.data,
          [`${keyName}ColType`]: keyColType,
          [`${valueName}ColType`]: valueColType
        }
        return itemData
      }
      const getChartData2 = () => {
        const {
          dimensions,
          measures
        } = this.value.params
        // console.log(this.value.params)
        const item = [...dimensions, ...measures].find(item => item.enName === source)
        colType = item.colType
        value = cell[source]
        return {
          value,
          colType
        }
      }

      let chartData
      switch (this.value.params.chartType) {
        // 分组表
        case 2:
          chartData = getChartData2()
          value = chartData.value
          colType = chartData.colType
          break
        // 明细表
        case 3:
          chartData = getChartData2()
          value = chartData.value
          colType = chartData.colType
          break
        // 柱状图
        case 4:
          // chartData = getChartData()
          // value = chartData[source]
          // colType = chartData[`${source}ColType`]
          chartData = getChartData2()
          value = chartData.value
          colType = chartData.colType
          break
        // 堆叠柱状图
        case 5:
          chartData = getChartData2()
          value = chartData.value
          colType = chartData.colType
          break
        // 条形图
        case 6:
          chartData = getChartData2()
          value = chartData.value
          colType = chartData.colType
          break
        // 折线图
        case 12:
          // chartData = getChartData()
          // value = chartData[source]
          // colType = chartData[`${source}ColType`]
          chartData = getChartData2()
          value = chartData.value
          colType = chartData.colType
          break
        // 面积图
        case 13:
          chartData = getChartData2()
          value = chartData.value
          colType = chartData.colType
          break
        // 堆叠折线图
        case 14:
          chartData = getChartData2()
          value = chartData.value
          colType = chartData.colType
          break
        default:
          break
      }
      if (value) {
        filter = {
          source,
          target,
          value,
          colType,
          key: componentKey
        }
      }
      return filter
    },
    // 更新标题
    updateTitle () {
      // console.log(this.option)
      if (this.option) {
        const {
          fontFamily, fontSize
        } = this.$store.state.lowCode.pageSetting.globalTitleStyle
        // 如果有全局配置
        if (fontFamily || fontSize) {
          this.option.title.style = {
            ...this.$store.state.lowCode.pageSetting.globalTitleStyle,
            fontSize: `${fontSize}px`
          }
        }
        // 如果没有, 则使用组件自己的配置
        else {
          const chartStyle = JSON.parse(this.value.chartStyle.replaceAll('\"{', '{').replaceAll('}\"', '}'))
          this.option.title.style = chartStyle.globeStyle?.title?.style || {}
        }
      }
    },
    handlePageChange (val) {
      this.getOptions(val)
    }
  },
  props: getProps(),
}
</script>

<style lang="less" scoped>
  .c-widget {
    // background: #999;
  }
</style>
